/***
 * f_upload
 * by chaituan@126.com
 */
(function($) {
	$.fn.__f_upload = function(options) {
		var that = this;
		var max = that.data('more')?that.data('more'):1;//最大文件个数
		var demoListView = that.next().next().find('.file_list');
		var files = {};
		var multiple = that.data('more')?true:false;
		var sub_act = that.next().next().find(":button");
		var thumb = that.next().next().next('.thumb').val().split(',');
		//预览
		edit();
		layui.upload.render({
			    elem: that,
			    multiple:multiple,
			    auto:false,
			    bindAction:sub_act,//指定上传按钮
			    size:1024,
			    exts:'jpg|png|gif|jpeg',
			    choose:function(obj){//选择文件后的回调函数
			    	var thumb_length = 0;
			    	if(thumb[0]){
			    		thumb_length = thumb.length;
			    		if(thumb_length >= max){
			    			$.each(obj.pushFile(),function(k){//框架里面 没有提供阻止上传的方法 这里自定义一个
				    			delete obj.pushFile()[k]
				    		})
				    		layer.msg("最多上传"+max+"张");
				    		return false;	
			    		}
			    	}
			    	if(Object.keys(files).length == 0){//点击选择图片后 打开绑定的上传图片功能
				   		that.next().next().next('.layui-upload').attr('class','layui-upload layui-show');//这里两个next 因为动态添加了
					}
			    	if((Object.keys(files).length + thumb_length) >= max){
						layer.msg("最多上传"+max+"张.");
						return false;
				    };
				    files = obj.pushFile(); //将每次选择的文件追加到文件队列
			    	var i = 0;
			    	obj.preview(function(index, file, result){
			    		if(i >= max){
			    			delete files[index];
			    			layer.msg("最多上传"+max+"张");
			    		}else{
			    			var tr = $(['<tr id="upload-'+ index +'"> '
				    		            ,'<td><img src='+ result +' layer-src='+ result +' style="width:22px;cursor:pointer"  ></td>'
				    		            ,'<td>'+ file.name +'</td>'
				    		            ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>'
				    		            ,'<td>等待上传</td>'
				    		            ,'<td>'
				    		              ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
				    		              ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
				    		            ,'</td>'
				    		          ,'</tr>'].join(''));
			 		          //单个重传
			 		          tr.find('.demo-reload').on('click', function(){
			 		            obj.upload(index, file);
			 		          });
			 		          //删除
			 		          tr.find('.demo-delete').on('click', function(){
			 		            delete files[index]; //删除对应的文件
			 		            tr.remove();
			 		          });
			 		          demoListView.append(tr);
			 		          layer.photos({photos:'#upload-'+ index});//添加预览
			 		          layer.tips('点击图片预览', '#upload-'+ index);//tips提醒
			    		}
			    		i++;
			    	});
				},
			    before:function(obj){
				    if(Object.keys(files).length==0){
				    	layer.msg('请选择要上传的文件');return false;
					}
			    	layer.open({
			    		  title:false,area: '500px',
			    		  content: '<div class="layui-progress" lay-showpercent="true" lay-filter="file_load">'
			    				+ '<div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>'
			    				+ '</div>',
			    		  closeBtn: false,btn:false,
			    		  success:function(){
			    		      //模拟loading
			    			  	layui.element.init();
			    			  	var n = 0, timer = setInterval(function(){
					    		    	n = n + Math.random()*10|0; 
					    		        if(n>100){
					    		          n = 99;
					    		          clearInterval(timer);
					    		        }
					    		        layui.element.progress('file_load', n+'%');
					    		      }, Math.random()*200);
						   }
			    	});
				},
			    done: function(d,index,upload){
			      //上传完毕回调
					if(d.state == 1){ //上传成功
			            var tr = demoListView.find('tr#upload-'+ index),tds = tr.children();
			            tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
			            tds.eq(4).remove(); //清空操作
			            delete files[index]; //删除文件队列已经上传成功的文件
			            var input = that.next().next().next().next('.thumb');
			            var url = d.data.url;
			            if(multiple){
			            	var r = input.val()?input.val()+","+url:url;
			            	input.val(r)
			            	thumb.push(r);
			            }else{
			            	input.val(url);
			            	thumb.push(url);
			            }
			            sub_act.remove();
			            layer.msg(d.message,{icon: d.state});
			            return;
			    	}else{
			    		layer.msg(d.message,{icon: d.state});
				       	this.error(index, upload,d.message);
				    }
			    },
			    error: function(index, upload,msg){
			      //请求异常回调
			    	var tr = demoListView.find('tr#upload-'+ index),tds = tr.children();
			        tds.eq(3).html('<span style="color: #FF5722;">'+msg+'</span>');
			        tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
			    }
		});
		//预览图片
		function edit(){
			if(thumb[0]){
				that.next().next('.layui-upload').attr('class','layui-upload layui-show');//这里两个next 因为动态添加了
				$.each(thumb,function(k,v){
					 var tr = $(['<tr class="upload"> '
		    		            ,'<td><img src='+ v +' layer-src='+ v +' style="width:22px;height:22px;cursor:pointer" class="img_del"  ></td>'
		    		            ,'<td colspan="3" style="color:#aaa;font-size:12px">注：删除后可以重新添加，删除则无法恢复，请慎重操作</td>'
		    		            ,'<td>'
		    		              ,'<button class="layui-btn layui-hide"></button>'
		    		              ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
		    		            ,'</td>'
		    		          ,'</tr>'].join(''));
					 tr.find('.demo-delete').on('click', function(){
							var del = $(this).parent().prev().prev().find('img').attr('src');
							layer.confirm('确定要执行当前操作？', {btn: ['是','否']}, function(index){
								layer.close(index);
								var l = loads();
								$.post('/images/upload/del.html',{thumb:del},function(d) {
						            tr.remove();
						            thumb.splice($.inArray(del.substr(1),thumb),1);
						            that.next().next().next().next('.thumb').val(thumb.join(','))
						            layer.msg("删除成功");
						            layer.close(l);
						        },'json');
							});
							return false;
					});
					demoListView.append(tr);
	 		        layer.photos({photos:'.upload'});//添加预览
				}); 
					//删除
			}
		}
}
	
$.fn.f_upload = function(options) {
	$(this).each(function(index, element) {
		$(element).__f_upload(options);
	});
}

})(jQuery);
